<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <img src="../stream.jpg" alt="加载中" style="width: 100%;" id="img">
    <script>
        const ws = new WebSocket("ws://127.0.0.1:81");
        ws.onopen = (event) => {
            console.log("连接服务器成功!");
            ws.send("Hello From Client!");
        }
        ws.onmessage = (event) => {
            // console.log("来自服务器:" + event.data);
            // 编码数据
            const reader = new FileReader();
            reader.onload = function () {
                const arrayBuffer = reader.result;
                const uint8Array = new Uint8Array(arrayBuffer);
                // console.log(uint8Array);
                // 转base64
                const base64String = btoa(String.fromCharCode.apply(null, uint8Array));
                // console.log(base64String);
                // 显示到img元素上
                let img = document.getElementById("img");
                img.src = "data:image/jpeg;base64," + base64String;
            };
            reader.readAsArrayBuffer(event.data);
        }
    </script>
</body>

</html>